package api

import (
	"context"

	"dev.ixmxm.top/rms/codes"
	"dev.ixmxm.top/rms/managers/robotmanager"
	"dev.ixmxm.top/rms/utils/log"
)

// @Summary 主动获取机器人外接传感器数据
// @Description
// @Accept application/json
// @Produce application/json
// @Param agv_id query string true "机器人ID"
// @Param sensor_type query int32 true "外接传感器类型ID"
// @Success 0 {object} ResponseExampleStruct "返回数据格式"
// @Success 1 {object} proto.SensorData "data数据：机器人外接传感器数据"
// @Tags 传感器
// @Router /sensor/get_robot_sensor_data [get]
func (hg *HttpGateway) GetRobotSensorData(ctx context.Context, params interface{}) (interface{}, codes.Code) {
	p := params.(*getSensorDataParams)
	caller, _ := hg.dispatcher.GetCaller(p.AgvID)
	if caller == nil {
		return nil, codes.ErrRobotOperate.WithDetails("没有找到小车连接")
	}
	robot := robotmanager.GetFromCache(p.AgvID)
	if robot.StatusIsExists() && robot.Status.Online {
		sensorData, err := caller.GetSensorData(ctx, p.SensorType)
		if err != nil {
			log.ErrorfWithContext(ctx, "主动获取设备读取的数据错误 error:%s", err.UnWrapError())
			return nil, err
		}
		return sensorData, nil
	}
	return nil, codes.ErrDeviceStatusNotMatch
}

// @Summary 主动给传感器写入数据
// @Description
// @Accept application/json
// @Produce application/json
// @Param body body setSensorDataParams true "传感器数据"
// @Success 0 {object} ResponseExampleStruct "返回数据格式"
// @Success 1 {object} proto.SensorData "data数据：机器人外接传感器数据"
// @Tags 传感器
// @Router /sensor/set_robot_sensor_data [post]
func (hg *HttpGateway) SetRFIDSensorData(ctx context.Context, params interface{}) (interface{}, codes.Code) {
	p := params.(*setSensorDataParams)
	log.Warnf("API 设置RFID数据：%+v", p)
	caller, _ := hg.dispatcher.GetCaller(p.AgvID)
	if caller == nil {
		return nil, codes.ErrRobotOperate.WithDetails("没有找到小车连接")
	}
	robot := robotmanager.GetFromCache(p.AgvID)
	if robot.StatusIsExists() && robot.Status.Online {
		sensorData, err := caller.SetSensorData(ctx, p.SensorType, p.WriteData)
		if err != nil {
			log.ErrorfWithContext(ctx, "设置设备RFID数据错误 error:%s", err.UnWrapError())
			return nil, err
		}
		return sensorData, nil
	}
	return nil, codes.ErrDeviceStatusNotMatch
}
